package com.jsz.peini.controller.app;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jsz.peini.bean.codes.SystemCity;
import com.jsz.peini.bean.comm.AppVersion;
import com.jsz.peini.bean.comm.AppVersionExample;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.bean.user.UserInfoExample;
import com.jsz.peini.bean.user.UserLogin;
import com.jsz.peini.common.bean.SmsVo;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.CommonUtils;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.mapper.comm.AppVersionMapper;
import com.jsz.peini.mapper.user.UserAccountMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.redis.util.UserRedisUtil;
import com.jsz.peini.service.sms.SmsService;
import com.jsz.peini.service.user.UserAccountService;
import com.jsz.peini.service.user.UserInfoService;
import com.jsz.peini.service.user.UserLoginService;

@Controller
public class UserInviteController {
	private static final Logger logger = LoggerFactory.getLogger(UserInviteController.class);
	@Resource
	private UserInfoMapper userInfoMapper;
	@Resource
	private UserInfoService userInfoService;
	@Resource
	private UserLoginService userLoginService;
	@Resource
	private UserAccountService userAccountService;
	@Resource
	private AppVersionMapper appVersionMapper;
	@Resource
	private SmsService smsService;
	@Resource
	private UserAccountMapper userAccountMapper;

	/**
	 * 用户登录
	 * @param userLogin
	 * @author zq
	 */
	@RequestMapping(value = "/invite/index")
	public Object index(HttpServletRequest request,
			@RequestParam(value="userPhone") String userPhone
			) {
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		// 用户名密码不能为空
		try {
			UserInfoExample example = new UserInfoExample();
			example.createCriteria().andUserPhoneEqualTo(userPhone);
			List<UserInfo> list = userInfoMapper.selectByExample(example);
			if(list.size()>0){
				UserInfo userInfo = list.get(0);
				userInfo.setNickname(PeiniUtils.updateNickName(userInfo.getNickname(), userInfo.getAccCode()));
				request.setAttribute("userInfo", userInfo);
				
				userInfo.getNowProvince();
				
				SystemCity province = PeiniUtils.cityMap.get(userInfo.getNowProvince().toString());
				if(province != null){
					request.setAttribute("provinceName", province.getCodesName());
				}
				
				SystemCity city = PeiniUtils.cityMap.get(userInfo.getNowCity().toString());
				if(city != null){
					request.setAttribute("cityName", city.getCodesName());
				}
			}
			request.getSession().setAttribute("imgHost", PeiniUtils.IMGHOST);
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		return "invite/index";
	}
	
	@RequestMapping(value = "/invite/download")
	public Object download(HttpServletRequest request
			) {
		AppVersionExample example = new AppVersionExample();
		List<AppVersion> list = appVersionMapper.selectByExample(example);
		for (AppVersion appVersion : list) {
			if(appVersion.getAppType() == 1){
				request.setAttribute("android", appVersion);
			}else{
				request.setAttribute("ios", appVersion);
			}
		}
		return "invite/download";
	}
	
	@ResponseBody
	@RequestMapping(value = "/invite/register")
	public Object register(HttpServletRequest request,
			@RequestParam(value="userName") String userName,
			@RequestParam(value="checkCode") String checkCode,
			@RequestParam(value="smsCode") String smsCode,
			@RequestParam(value="pass") String pass,
			@RequestParam(value="recId") String recId,
			@RequestParam(value="channel",required=false,defaultValue="") String channel,
			@RequestParam(value="devtype",required=false) Integer devtype
			) {
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		// 用户名密码不能为空
		try {
			/*if(request.getSession().getAttribute("authCode") == null){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "请刷新验证码");
				return infoMap;
			}
			
			if(!request.getSession().getAttribute("authCode").toString().toLowerCase().equals(checkCode.toLowerCase())){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "图片验证码不正确");
				return infoMap;
			}*/
			
			SmsVo smsVo = UserRedisUtil.getSmsVo(userName);
			if (smsVo == null) {
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "您输入的手机验证码不正确");
				return infoMap;
			} else {
				//SmsVo smsVo = (SmsVo)yzmObject;
				String yzmCode = smsVo.getYzm();
				Date sendTime = smsVo.getSendTime();
				
				// 验证码通过则清除验证码
				if (yzmCode.equals(smsCode)) {
					
					//判断是否超时
					Date now = new Date();
					if(now.getTime()-sendTime.getTime() > 60*1000){
						infoMap.put("resultCode", Constants.FAIL);
						infoMap.put("resultDesc", "验证码已超时请重新获取");
						return infoMap;
					}
					
					UserRedisUtil.delSmsVo(userName);
				} else {
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "您输入的手机验证码不正确");
					return infoMap;
				}
			}
			
			infoMap = userInfoService.register_invite(request, userName, checkCode, smsCode, pass, recId, channel, devtype);
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		return infoMap;
	}
	
	/**
	 * 手机号注册验证码发送接口
	 * 
	 * @param userLogin
	 * @author jgx
	 */
	@RequestMapping(value = "/invite/smsSendRegister")
	@ResponseBody
	public Object smsSend(HttpServletRequest request,
			@RequestParam(value="userName") String userName,
			@RequestParam(value="checkCode") String checkCode
			) {
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		try {
			
			if(StringUtils.isBlank(userName)){
				infoMap.put("resultCode", Constants.EXCEPTION);
				infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
			}
			
			/*if(request.getSession().getAttribute("authCode") == null){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "请刷新验证码");
				return infoMap;
			}
			
			if(!request.getSession().getAttribute("authCode").toString().toLowerCase().equals(checkCode.toLowerCase())){
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "图片验证码不正确");
				return infoMap;
			}*/
			
			UserLogin userLoginBean = userLoginService.selectByUserName(userName);
			if (userLoginBean == null) {
				// 生成验证码
				String yzm = CommonUtils.createRandom(true, 6);
				logger.info("-----------------手机验证码:-----------------------"+yzm);
				SmsVo smsVo = new SmsVo(yzm,new Date());
				
				// 发送验证码
				boolean smsResult = smsService.sendMessage(userName, yzm, Constants.SMS_YZM);
				// boolean smsResult = true;//测试用
				if (smsResult) {
					infoMap.put("resultCode", Constants.SUCCESS);
					infoMap.put("resultDesc", "已发送");
				} else {
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "您输入的手机号格式不正确");
				}
				//EhcacheUtil.getInstance().put("smsCache", userName, smsVo);
				UserRedisUtil.updateTelAuthcode(userName, smsVo);
				
				infoMap.put("userName", userName);
				//logger.info(yzm);
				//infoMap.put("smsCode", yzm);// 测试用
			} else {
				infoMap.put("userName", userName);
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "您输入的手机号已注册");
			}
		} catch (Exception e) {
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
			logger.error(e.getMessage(),e);
		}
		return infoMap;
	}

	/**
	 * 图片验证码
	 * @author Han Guohong
	 * @param request
	 * @param response
	 * @param session
	 * @throws IOException
	 */
	@RequestMapping({"authCode"})
    public void getAuthCode(HttpServletRequest request, HttpServletResponse response,HttpSession session)
            throws IOException {
        int width = 115;
        int height = 35;
        Random random = new Random();
        //设置response头信息
        //禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //生成缓冲区image类
        BufferedImage image = new BufferedImage(width, height, 1);
        //产生image类的Graphics用于绘制操作
        Graphics g = image.getGraphics();
        //Graphics类的样式
        //g.setColor(this.getRandColor(200, 250));
        g.setColor(Color.GRAY);
        g.setFont(new Font("Times New Roman",0,28));
        g.fillRect(0, 0, width, height);
        //绘制干扰线
        for(int i=0;i<40;i++){
            g.setColor(this.getRandColor(130, 200));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(12);
            int y1 = random.nextInt(12);
            g.drawLine(x, y, x + x1, y + y1);
        }

        //绘制字符
        String strCode = "";
        for(int i=0;i<4;i++){
            //String rand = String.valueOf(random.nextInt(10));
        	String rand = String.valueOf(randomChar());
            strCode = strCode + rand;
            g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
            g.drawString(rand, 18*i+6, 28);
        }
        //将字符保存到session中用于前端的验证
        session.setAttribute("authCode", strCode);
        //logger.info(strCode);
        g.dispose();

        ImageIO.write(image, "JPEG", response.getOutputStream());
        response.getOutputStream().flush();

    }
	
	private char randomChar(){  
        Random r = new Random();  
        String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";  
        return s.charAt(r.nextInt(s.length()));  
    } 
	
	Color getRandColor(int fc,int bc){
        Random random = new Random();
        if(fc>255)
            fc = 255;
        if(bc>255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r,g,b);
    }
}
